package rjeutsky.ui;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import rjeutsky.utilities.StringUtility;

public class EnumConsoleRequest<E extends Enum<E>> extends ConsoleRequest<Enum<E>> {

	public EnumConsoleRequest(E defaultValue){
		if (defaultValue == null){
			throw new NullPointerException("default value should be any value of enum specified");
		}
		
		value = defaultValue;
	}
	
	@Override 
	protected void showRequest() {
		Enum<?>[] variants = value.getClass().getEnumConstants();
		List<Object> variantTexts = new LinkedList<Object>();
		for (Enum<?> e : variants){
			variantTexts.add(e.name());
		}
		
	    String textToShow = String.format("%1$s (%2$s)", requestText, StringUtility.join(variantTexts, ", "));
	    System.out.println(textToShow);
	}
		
	@SuppressWarnings("unchecked")
	@Override
	protected void queryConsole() {
		// must be of type e - initialized in constructor
		Enum<E>[] variants = value.getClass().getEnumConstants();
		Scanner scanner = new Scanner(input);
		String line = "";
		while (true){
			line = scanner.nextLine();
			for (Enum<E> variant : variants){
				if (line.equalsIgnoreCase(variant.name())){
					value = variant;
					return;
				}
			}
		}
	}
}
